﻿using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Text;

namespace MPNet6.Client.ServerSend;

internal record MPMessage(string Host, int Port, byte[] SendBuffer);
public static class MPClientSend
{
    private static BlockingCollection<MPMessage> _Messages = new();
    private static ILogger _Logger = default!;
    public static void Start(ILogger logger)
    {
        _Logger = logger;
        Task.Run(async () =>
        {
            var recBuffer = new byte[8];
            foreach (var mpMsg in _Messages.GetConsumingEnumerable())
            {
                var cts = new CancellationTokenSource(TimeSpan.FromSeconds(8));
                try
                {
                    var tcpClient = new TcpClient()
                    {
                        ReceiveBufferSize = 8,
                        SendBufferSize = 64 * 1024
                    };
                    await tcpClient.ConnectAsync(mpMsg.Host, mpMsg.Port);
                    var stream = tcpClient.GetStream();
                    await stream.WriteAsync(mpMsg.SendBuffer, cts.Token);
                    if (await stream.ReadAsync(recBuffer, cts.Token) <= 0)
                        _Messages.Add(mpMsg);
                }
                catch (Exception ex)
                {
                    _Logger.LogWarning(ex.Message);
                    _Messages.Add(mpMsg);
                }
                finally
                {
                    cts.Dispose();
                }
            }
        });
    }


    public static void Send(string host, int port, string receiveMessageClientId, string message)
    {
        var buffer = Encoding.ASCII.GetBytes($"\u0004{receiveMessageClientId}\t{message}");
        if (buffer.Length > 64 * 1024)
            throw new Exception("要发送的内容不能超过64K");
        _Messages.Add(new(host, port, buffer));
    }
    public static void Stop()
    {
        _Messages.CompleteAdding();
        while (!_Messages.IsCompleted)
            Thread.Sleep(500);
    }
}